﻿using System;
using UnityEngine;

namespace Framework
{
    public class TimeCounter : ReferenceCountable
    {
        protected float _interval;
        protected int _invokeCount;
        protected Action<float> _callback;

        protected int _invokeCounter;
        protected float _lastStartTime;
        
        public TimeCounter(float interval, int invokeCount, Action<float> callback)
        {
            _interval = interval;
            _invokeCount = invokeCount;
            _callback = callback;
        }
        
        public bool Update()
        {
            float curTime = Time.realtimeSinceStartup;
            float deltaTime = curTime - _lastStartTime;
            if (deltaTime >= _interval)
            {
                _callback.Invoke(deltaTime);
                _lastStartTime = curTime;
                ++_invokeCounter;
                if (_invokeCount > 0 && _invokeCounter >= _invokeCount)
                {
                    return true;
                }
            }
            return false;
        }

        public override bool Equals(object obj)
        {
            return _callback == (Action<float>)obj;
        }

        public void Reset()
        {
            _invokeCounter = 0;
            _lastStartTime = Time.realtimeSinceStartup;
        }
    }
}